package cn.com.dstz.data.post;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.jsoup.Connection.KeyVal;

/**
 * 数据POST
 * 在该类中要POST数据到多个IP上
 * @author 叶装装
 */
public class Post implements Runnable{
	
	private String [ ] ipAddrs;	// 服务器IP地址
	private KeyVal keyVal;
	
	public Post( ){}
	
	public Post( String [ ] ipAddrs, KeyVal keyVal ){
		this.ipAddrs = ipAddrs;
		this.keyVal = keyVal;
	}
	
	public void post( ){
		
		DefaultHttpClient httpClient = new DefaultHttpClient( );
		setParams( httpClient, CoreConnectionPNames.CONNECTION_TIMEOUT,  300 ); // 单位毫秒, 连接超时
		setParams( httpClient, CoreConnectionPNames.SO_TIMEOUT,  500 ); // 单位毫秒, 发送数据超时
		try{
			for( int i = 0; i < ipAddrs.length; i++ ){
				String ip = ipAddrs[ i ];
		
				HttpPost httpost = new HttpPost( ip );
						
				StringEntity myEntity = new StringEntity( PostKeyVal.DEFAULT_POST_KEY + "=" + keyVal.value( ),  ContentType.create( "text/plain", "GBK" ) );
						
				httpost.setEntity( myEntity );
				try{
					httpClient.execute(httpost);
				}catch( Exception e ){
					String msg = e.getMessage( );
					if( "!Read timed out".equals( msg ) ){
						e.printStackTrace( );
					}
					
				}
					
			}
		}finally{
			 httpClient.getConnectionManager().shutdown();
		}
		
	}
	
	public void run( ) {
		post( );
	}
	
	private void setParams( DefaultHttpClient httpClient, String name, Object value ){
		HttpParams httpParams = httpClient.getParams( );
		httpParams.setParameter( name, value );
	}
	
	public String [ ] getipAddrs( ) {
		return ipAddrs;
	}

	public void setIpAddrs( String [ ] ipAddrs ) {
		this.ipAddrs = ipAddrs;
	}

	public KeyVal getKeyVal( ) {
		return keyVal;
	}

	public void setKeyVal( KeyVal keyVal ) {
		this.keyVal = keyVal;
	}
	
	public static void main( String [ ] args ) {
		//223.4.208.29
		//112.125.92.65
		
		String [] ips = new String[]{
			//	"http://223.4.208.29:9009",
				"http://112.125.92.65:9009"
		};
		
//		ips = new String[]{
//				"http://www.a.com/a/ajaxAct!t1.action",
//				"http://www.a.com/a/ajaxAct!t2.action",
//			//"http://223.4.208.29:9009"
//		};
		
		NoticeKeyVal val = new NoticeKeyVal( 1, "发送数据发送数 " );
		Post post = new Post( ips, val);
		post.post( );
	}
}
